package com.google.code.mongoDao;

import java.util.Set;

import org.apache.log4j.Logger;

import com.google.inject.Inject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

/**
 * Util class for performing generic database operations
 * 
 * @author MWaschkowski
 *
 */
public class DatabaseUtil {

  private DB db;
  
  private Logger logger = Logger.getLogger(DatabaseUtil.class);
  
  @Inject
  public DatabaseUtil(DB db) {
    this.db = db;
  }
 
  /**
   * Drops the specified collection from the database
   * 
   * @param collectionName
   */
  public void dropCollection(final String collectionName){
    logger.debug("Dropping collection: " + collectionName);
    db.getCollection(collectionName).drop();
    logger.debug("Dropped: " + collectionName);
  }
 
  /**
   * Drops the whole database
   */
  public void dropDatabase(){
    logger.debug("Dropping database...");
    db.dropDatabase();
    logger.debug("Database dropped");
  }
  
  /**
   * Ensures an index has been created for a collection
   * 
   * @param collectionName
   * @param dbObject
   */
  public void ensureIndex(String collectionName, DBObject dbObject){
    DBCollection collection = db.getCollection(collectionName);
    collection.ensureIndex(dbObject);
  }
  
  /**
   * Determines if a collection exists
   * 
   * @param collectionName
   * @return
   */
  public boolean collectionExists(String collectionName){
    return db.collectionExists(collectionName);
  }
  
  /**
   * Gets all the collection names for a database
   * @return
   */
  public Set<String> getCollectionNames(){
    return db.getCollectionNames();
  }

  public DB getDb(){
    return db;
  }
  
}
